package com.caiyi.financial.nirvana.sms.queue;

import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.service.SmsUserService;
import com.caiyi.financial.nirvana.sms.task.UpdateBalanceTask;
import com.caiyi.financial.nirvana.sms.util.ThreadPoolUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 更新余额
 */
@Component
public class UpdateBalanceQueue implements IRedisQueue {

    private static final int UPDATE_BALANCE = 10 * 1000;

    private long startTime = System.currentTimeMillis();

    @Autowired
    private SmsUserService smsUserService;

    @Override
    public String key() {
        return JedisKey.SMS_QUEUE_BALANCE_UPDATE;
    }

    public void run(List<String> list) {
        if (list != null && !list.isEmpty()) {
            String[] accountSmsNum = list.get(1).split("=");
            String account = accountSmsNum[0];
            Long msgCount = Long.valueOf(accountSmsNum[1]);
            JedisService.hincrBy(JedisKey.SMS_UPDATE_BALANCE, account, msgCount);
        }
        if ((System.currentTimeMillis() - this.startTime) > UPDATE_BALANCE) {
            Map<String, String> map = JedisService.hgetAll(JedisKey.SMS_UPDATE_BALANCE);
            for (Map.Entry<String, String> entry : map.entrySet()) {
                UpdateBalanceTask task = new UpdateBalanceTask(smsUserService, entry.getKey(), Integer.valueOf(entry.getValue()));
                ThreadPoolUtil.EXECUTOR_UPDATE_BALANCE.execute(task);
            }
            JedisService.del(JedisKey.SMS_UPDATE_BALANCE);
            //重置时间
            this.startTime = System.currentTimeMillis();
        }
    }

    @Override
    public void interrupt(Exception e) {

    }
}
